package tt.dz.egobus.servicemanager.business.distance;

import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.iterators.FilterIterator;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tt.dz.egobus.servicemanager.business.point.BusPoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @author Anson
 * @date 17-3-23
 * @name 默认实现算法
 * @since 1.0.2
 */
public class DefaultDistanceAlgorithm extends AbstractDistanceAlgorithm {

    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultDistanceAlgorithm.class);

    public static final String ID = "default";


    @Override
    public String id() {
        return ID;
    }

    @Override
    public BusPoint[] bestQueue(PointFilter pointFilter) {
        BusPoint[] filters = this.getFilter(pointFilter);
        Arrays.sort(filters, new DistanceComparator(this.x, this.y));
        return filters.length > this.queueLimit ? ArrayUtils.subarray(filters, 0, this.queueLimit) : filters;
    }

    @Override
    public BusPoint[] getFilter(final PointFilter pointFilter) {
        //若果当前并没有限制的杀死后，直接返回
        final boolean isLimitDis = !this.isUnlimitDistance();
        final boolean isContainFilter = pointFilter != null;
        LOGGER.info("地图算法过滤,isLimitDis={},isContainFilter={}",
                isLimitDis, isContainFilter);
        if (!isLimitDis && !isContainFilter) {
            LOGGER.info("地图算法过滤,当前不过滤");
            return this.busPoints.toArray(new BusPoint[this.busPoints.size()]);
        }
        List<BusPoint> list = new ArrayList<BusPoint>(0);
        //存在最大距离筛选的时候
        Iterator<BusPoint> iterator = new FilterIterator(this.busPoints.iterator(), new Predicate<BusPoint>() {
            @Override
            public boolean evaluate(BusPoint o) {
                boolean isSuccess = true;
                //当前提供了额外的过滤方法
                if (isSuccess && isContainFilter) {
                    isSuccess = pointFilter.isFilter(o);
                }
                if (0 == o.x() || 0 == o.y()) {
                    LOGGER.debug("当前的坐标存在0,point={}", o);
                }
                return isSuccess;
            }
        });
        while (iterator.hasNext()) {
            list.add(iterator.next());
        }
        LOGGER.info("当前过滤后的坐标集合为getFilter={}", list.size());
        return list.toArray(new BusPoint[list.size()]);
    }

}
